<?php

namespace App\Http\Services;


/*充值订单service层*/

use App\Http\Model\Device;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\Hint;
use App\Http\Model\SystemConfig;
use App\Http\Model\User;
use App\Http\Model\UserRegisterLog;
use App\Http\Model\UserVerify;
use App\Lib\DingDingRobot;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Http\Services\PlatformReportServices;
use App\Http\Model\RechargeBlack;
use App\Http\Model\System;
use App\Http\Services\ThinkingdataServices;
use App\Lib\rc;
use Carbon\Carbon;

class FinanceRechargeOrderServices extends CommonServices
{
    protected $user;
    protected $diamond;
    protected $rechargeOrder;
    protected $config;
    protected $userVerifyModel;
    protected $dingDingRobot;
    protected $userRegisterLogModel;
    protected $deviceModel;
    protected $deviceServices;
    protected $platformReportServices;
    protected $rechargeBlackModel;
    protected $tdService;
    protected $comBackService;
    protected $systemModel;
    protected $lib_rong;

    protected $showFullScreenUserListKey = 'SHOW:FULLSCREEN:USERLIST';//zset 满足系统配置显示全局飘屏用户列表SHOW:FULLSCREEN:USERLIST=>{userid}
    protected $payOrderCountRedisKey = 'PAY:ORDER:COUNT:USER:';//string 用户未支付下订单次数 PAY:ORDER:COUNT:USER:{int}
    protected $payOrderLimitReidsKey = 'PAY:ORDER:FINASH:USER:';//string 用户成功支付渠道支付间隔
    protected $payOrderFiveMinutes = 'PAY:ORDER:FIVE:MINUTES:';//string 用户未支付3次缓存
    protected $payOrderFiveMinutesCount = 'PAY:ORDER:FIVE:MINUTES:COUNT:';//记录加入3次未支付的次数

    /**
     * @var UserServices
     */
    protected $userService;

    public function __construct(User $user, FinanceDiamond $diamond, FinanceRechargeOrder $rechargeOrder,UserRegisterLog $userRegisterLogModel ,Device $deviceModel,DeviceServices $deviceServices)
    {
        parent::__construct();

        $this->user = $user;
        $this->diamond = $diamond;
        $this->rechargeOrder = $rechargeOrder;
        $this->config = config('pay');
        $this->userVerifyModel = new UserVerify();
        $this->dingDingRobot = new DingDingRobot();
        $this->userRegisterLogModel = $userRegisterLogModel;
        $this->deviceModel = $deviceModel;
        $this->deviceServices = $deviceServices;
        $this->userService = new UserServices();
        $this->platformReportServices = new PlatformReportServices();
        $this->rechargeBlackModel = new RechargeBlack();
        $this->tdService = new ThinkingdataServices();
        $this->comBackService = new ComeBackServices();
        $this->systemModel = new System();
        $this->lib_rong = new rc();

    }

    //创建订单
    public function createRechargeOrder($userId, $rule_id, $pay_type, $plat_type,$rechargeType = 0 ,$custom_price=0, $payConfigName='',$first_recharge_id="")
    {
        $result = [];
        // 充值规格
        $ruleInfo = [];

        //判断充值类型获取规格数据
        switch ($rechargeType){
            case 0://钻石
                if ($plat_type == 1) {//iOS
                    $ruleInfo = $this->diamond->getDiamondRuleIos($rule_id);
                } elseif ($plat_type == 2) {//android
                    $ruleInfo = $this->diamond->getDiamondRuleAndroid($rule_id);
                } elseif ($plat_type == 3) {//apple内购
                    $ruleInfo = $this->diamond->getDiamondRuleApple($rule_id);
                }elseif (in_array($plat_type,[4,6])) {//h5充值
                    $ruleInfo = $this->diamond->getDiamondRuleMp($rule_id);
                }
                break;
            case 1://

                break;
            default:
                break;
        }
        if ($custom_price) {
            $rule_id = 0;
            $ruleInfo = [
                'rule_id' => 0,
                'price' => $custom_price * 100,
                'diamond_amount' => $custom_price * 10,
                'plat_type' => $plat_type,
                'first_recharge_id' => $first_recharge_id
            ];
        }
        if (empty($ruleInfo)) {
            return false;
        }

        $userInfo = $this->user->get_user($userId);
        if (empty($userInfo)) {
            return false;
        }

        if($this->reachRechargeToplimit($userInfo['user_id'])){
            return Hint::FINANCE_RECHARGE_TOPLIMIT;
        }

        if (!redis_lock('LOCK:FINANCE_ORDER_PAY' . $userInfo['user_id'], 1)) {
            return Hint::SAME_TIME_NOT_REPEAT;
        }

        $order_sn = create_recharge_order_sn();
        //三方支付规定订单参数必须20位以内
        if(in_array($pay_type,[9,10])){
            $order_sn = date('ymdhis') . date('Ym') . str_pad(mt_rand(1, 99), 2, '0', 0);
        }

        $user_id = $userInfo['user_id'];
        $channel_id = $userInfo['channel_id'];
        $price = $ruleInfo['price'];
        //获取当前使用的配置商户号
        $mch_id = 0;

        $configMchId = "";
        switch($payConfigName){
            case 'pay_wx_app_1':
                $config = (new SystemConfig)->getPayWxApp1();
                break;
            case 'pay_wx_app_2':
                $config = (new SystemConfig)->getPayWxApp2();
                break;
            case 'pay_wx_app_3':
                $config = (new SystemConfig)->getPayWxApp3();
                break;
        }
        $config = explode(',', $config);
        $config = array_filter($config);
        if (isset($config[0]) && trim($config[0]) && isset($config[1]) && trim($config[1]) && isset($config[2]) && trim($config[2])) {
            $configMchId = $config[1];
        }
// $payConfig = $this->config[$payConfigName];
        if($pay_type == 2){
            // $mch_id = $payConfig['mch_id'];
            $mch_id = $configMchId;
        }elseif($pay_type == 1){
//            $mch_id = $payConfig['alipay_user_id'];
            $mch_id = '2021004156624058';
        }
        //充值黑名单 TODO 注释校验
        $payBlack = $this->checkUserInRechargeBlack($user_id, $pay_type);
        /*if($payBlack) {
            return Hint::FINANCE_RECHARGE_BLACK;
        }*/

        /*
        //检查是否实名,是否未成年,-1.未找到\0.未成年\1.成年
        $status = (new UserVerify())->isAdult($user_id);
        //未成年：土司提示-为呵护未成年人健康成长，未成年人不允许充值（未满18岁）
        if ($status == 0) {
            return Hint::JUVENILES_NOT_REWARD_NEW_MSG;
        }
        //可充值，限额日400，累计2000
        if ($status == -1) {
            $recharge = $this->user->getNoRealIsAllowRecharge($user_id, $price);
            if (!$recharge) {
                return Hint::NOT_REAL_NAME_RECHARGE_LIMIT;
            }
        }
        */
        $unpayCount = Redis::GET($this->payOrderFiveMinutesCount.$userInfo['user_id'].':PAYTYPE:'.$pay_type);
        $unpayCount = empty($unpayCount) ? 0 : $unpayCount;

        if($unpayCount >= 2 ){
            $this->rechargeBlackModel->addRechargeBlack($userInfo['user_id'],'以往24小时内,累计自动进入5分钟黑名单3次',$pay_type);
        }else{
            //查看用户是否有未支付订单3个及以上
            if(!empty(Redis::get($this->payOrderCountRedisKey.$userInfo['user_id'].':PAYTYPE:'.$pay_type))){
                $count = Redis::get($this->payOrderCountRedisKey.$userInfo['user_id'].':PAYTYPE:'.$pay_type);
//                if($count >= 2){
                if($count >= 7){
                    Redis::SET($this->payOrderFiveMinutes.$userInfo['user_id'].':PAYTYPE:'.$pay_type,1);
                    Redis::EXPIRE($this->payOrderFiveMinutes.$userInfo['user_id'].':PAYTYPE:'.$pay_type, 300);
                    Redis::INCRBY($this->payOrderFiveMinutesCount.$userInfo['user_id'].':PAYTYPE:'.$pay_type,1);
                    $endDay = Carbon::now()->endOfDay();
                    $endTime = Carbon::now()->diffInSeconds($endDay);
                    Redis::EXPIRE($this->payOrderFiveMinutesCount.$userInfo['user_id'].':PAYTYPE:'.$pay_type,$endTime);

                    //临时5分钟表记录,只是记录未有业务操作
                    $this->rechargeBlackModel->addRechargeFiveMinutesBlack($userInfo['user_id'],$pay_type);
                }
            }
        }




        //对指定用户进行每日充值限制 start
        $dayPrice = 0;
        $user_limit = $this->user->getUserRechargeLimit($user_id);
        if(!empty($user_limit) && !empty($user_limit['value'])){
            $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $dayPrice = $this->rechargeOrder->getUserPayPrice($user_id, $beginToday, $endToday);
            if(($dayPrice+$price)>$user_limit['value']){
                return Hint::FINANCE_RECHARGE_DAY_LIMIT;
            }
        }

        // TODO 判断充值类型使用参数
        $diamondAmount = 0;// 钻石数量
        switch ($rechargeType){
            case 0://钻石
                $diamondAmount = $ruleInfo['diamond_amount'] ?? 0;
                break;
            case 1://

                break;
            default:
                break;
        }
//        write_log('createRes', '1111', json_decode($pay_type, true));
        $orderId = $this->rechargeOrder->create_order($order_sn, $user_id, $rule_id, $diamondAmount, $price, $pay_type, $channel_id,0,$rechargeType, $mch_id,$first_recharge_id);
        if($orderId > 0) {
            $result['orderId'] = $orderId;
//            write_log('createRes', '2222', json_decode($orderId, true));
            //埋点
            $this->tdService->handleTrack('order_payment_start', ['user_id'=>$user_id, 'order_id'=>$orderId]);

            return $result;
        }
        return false;
    }


    /**
     * 创建UID充值订单
     * @param $user_uid
     * @param $rule_id
     * @param $pay_type
     * @param $plat_type
     * @param int $rechargeType
     * @param $custom_price
     * @return bool|int
     */
    public function createUidRechargeOrder($user_uid, $rule_id, $pay_type, $plat_type,$rechargeType = 0 ,$custom_price)
    {
        $result = [];
        // 充值规格
        $ruleInfo = [];

        // TODO 判断充值类型获取规格数据
        switch ($rechargeType){
            case 0:// 钻石
                if(!empty($rule_id)){
                    $ruleInfo = $this->diamond->getDiamondRuleMp($rule_id);
                }else{
                    $ruleInfo = [
                        'rule_id' => 0,
                        'price' => $custom_price * 100,
                        'diamond_amount' => $custom_price * $this->diamond->getRechargeRatio(),
                        'plat_type' => $plat_type
                    ];
                }
                break;
            case 1:// 珍珠

                break;
            default:
                break;
        }

        if (empty($ruleInfo)) {
            return false;
        }
        $userInfo = $this->user->get_user_by_uid($user_uid);
        if (empty($userInfo)) {
            return Hint::USER_IS_NOT_EXIST;
        }

        if (!redis_lock('LOCK:FINANCE_ORDER_H5_PAY' . $userInfo['user_id'], 1)) {
            return Hint::SAME_TIME_NOT_REPEAT;
        }

        $order_sn = create_recharge_order_sn();
        $user_id = $userInfo['user_id'];
        $channel_id = $userInfo['channel_id'];
        $price = $ruleInfo['price'];

        //充值黑名单
        $payBlack = $this->checkUserInRechargeBlack($user_id, $pay_type);
        if($payBlack) {
            return Hint::FINANCE_RECHARGE_BLACK;
        }

        //查看用户是否有未支付订单3个及以上
        if(!empty(Redis::get($this->payOrderCountRedisKey.$userInfo['user_id'].':PAYTYPE:'.$pay_type))){
            $count = Redis::get($this->payOrderCountRedisKey.$userInfo['user_id'].':PAYTYPE:'.$pay_type);
            $isset = $this->checkUserInRechargeBlack($userInfo['user_id'], $pay_type);
            if($count >= 3 && $isset == 0){
                //记录到黑名单
                //if(!checkAppEnv()) {
                    $this->rechargeBlackModel->addRechargeBlack($userInfo['user_id'],'以往24小时内未支付订单超过3笔',$pay_type);
                //}
            }
        }

        //检查是否实名,是否未成年,-1.未找到\0.未成年\1.成年
        $status = (new UserVerify())->isAdult($user_id);
        //未成年：土司提示-为呵护未成年人健康成长，未成年人不允许充值（未满18岁）
        if ($status == 0) {
            return Hint::JUVENILES_NOT_REWARD_NEW_MSG;
        }
        //可充值，限额日400，累计2000
        if ($status == -1) {
            $recharge = $this->user->getNoRealIsAllowRecharge($user_id, $price);
            if (!$recharge) {
                return Hint::NOT_REAL_NAME_RECHARGE_LIMIT;
            }
        }

        //对指定用户进行每日充值限制 start
        $dayPrice = 0;
        $user_limit = $this->user->getUserRechargeLimit($user_id);
        if(!empty($user_limit) && !empty($user_limit['value'])){
            $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $dayPrice = $this->rechargeOrder->getUserPayPrice($user_id, $beginToday, $endToday);
            if(($dayPrice+$price)>$user_limit['value']){
                return Hint::FINANCE_RECHARGE_DAY_LIMIT;
            }
        }

        // TODO 判断充值类型使用参数
        $diamondAmount = 0;// 钻石数量
        switch ($rechargeType){
            case 0:// 钻石
                $diamondAmount = $ruleInfo['diamond_amount'] ?? 0;
                break;
            case 1://

                break;
            default:
                break;
        }

        //未实名，存入充值金额
        if ($status == -1) {
            Redis::INCRBY(User::NO_REAL_NAME_RECHARGE_TOTAL_NUM . $user_id, $diamondAmount);
            Redis::INCRBY(User::NO_REAL_NAME_RECHARGE_DAY_NUM . $user_id . ':' . date('Ymd'), $diamondAmount);
            Redis::expire(User::NO_REAL_NAME_RECHARGE_DAY_NUM . $user_id . ':' . date('Ymd'), 86400);
        }

        $orderId = $this->rechargeOrder->create_order($order_sn, $user_id, $rule_id, $diamondAmount, $price, $pay_type, $channel_id,0,$rechargeType);
        if($orderId > 0) {
            $result['orderId'] = $orderId;

            //埋点
            $this->tdService->handleTrack('order_payment_start', ['user_id'=>$user_id, 'order_id'=>$orderId]);

            return $result;
        }
        return false;
    }

    //获取订单
    public function getRechargeOrder($order_id)
    {
        if (!$order_id) {
            return false;
        }
        return $this->rechargeOrder->getOrder($order_id);
    }


    //获取订单
    public function getRechargeOrderSn($order_sn)
    {
        if (!$order_sn) {
            return false;
        }
        return $this->rechargeOrder->getOrderBySn($order_sn);
    }

    //更改订单状态
    //操作钱包
    //钻石流水
    public function notifyOp($order_sn = '', $out_trade_sn = '', $payType='')
    {
        if (!redis_lock('NOTIFYOP' . $order_sn, 30)){
            write_log("app_pay", "notifyOp-01", $order_sn . ' - ' . $out_trade_sn);
            return false;
        }
        $orderInfo = $this->rechargeOrder->getOrderByOutsn($out_trade_sn);
        if ($orderInfo != null){
            write_log("app_pay", "notifyOp-02", $order_sn . ' - ' . $out_trade_sn);
            return false;
        }
        $orderInfo = $this->rechargeOrder->getOrderBySn($order_sn);
        if (empty($orderInfo)){
            write_log("app_pay", "notifyOp-03", $order_sn . ' - ' . $out_trade_sn);
            return false;
        }
        $report_price = !empty($orderInfo['price']) ? $orderInfo['price']/100 : 0;
        if($orderInfo['status'] == 0){
            $desc = $this->config['wallet_change_desc']['recharge_diamond'];
            $user_id = $orderInfo['user_id'];

            DB::beginTransaction();

            // //支付宝额外奖励
            // if($payType==1 || $payType==6) {
            //     $diamond_extra_num = intval($orderInfo['diamond_amount'] * 0.01);
            //     $ruleInfo = $this->diamond->getDiamondRule($orderInfo['rule_id']);
            //     if(!empty($ruleInfo)) {
            //         $diamond_extra_num = $ruleInfo['diamond_extra_num'];
            //     }
            //     $orderInfo['diamond_amount'] = $orderInfo['diamond_amount']+$diamond_extra_num;

            //     $this->rechargeOrder->changeOrderDiamondAmount($order_sn, $orderInfo['diamond_amount']);
            // }

            $this->rechargeOrder->changeOrderStatus($order_sn, $out_trade_sn);

            // TODO 判断充值类型更新流水
            switch ($orderInfo['recharge_type'] ?? 0){
                case 0:// 钻石
                    $this->diamond->inc($user_id, 0, 0,3,$orderInfo['diamond_amount'] ?? 0,$desc);
                    $needSendMq = 1;
                    break;
                default:
                    break;
            }

            DB::commit();

            if(!empty($needSendMq) && $needSendMq==1) {
                $this->rechargeOrder->orderPaySuccessToMQ($order_sn, $orderInfo['user_id']);
            }

            //若是首次充值的则记录到首充用户表里
            $isfirstRecharge = $this->rechargeOrder->isFristRecharge($user_id);
            //充值规定金额6元
            $price = 600;
            if(!empty($isfirstRecharge['count']) && !empty($isfirstRecharge['orderinfo']) && $isfirstRecharge['count'] ==1 && $isfirstRecharge['orderinfo']['price'] >=$price)
            {
                $data['user_id'] = $orderInfo['user_id'];
                $data['has_ticket'] = 0;
                $data['luck_draw_user_prop_id'] = 0;
                $data['create_time'] = date("Y-m-d",time());
                $this->rechargeOrder->writeFirstRechargeLog($data);
            }
            redis_unlock('NOTIFYOP' . $order_sn);
            write_log("app_pay", "notifyOp-04", $user_id);
            if(!empty($user_id)){
                $this->report($user_id ,2 ,$report_price);
            }
            //首冲礼包订单
            if (!empty($orderInfo["first_recharge_id"])) {
                //赠送 记录 发放礼物
                $this->userService->setBackFirstRecharge($orderInfo["user_id"],$orderInfo["first_recharge_id"],$orderInfo["price"],$orderInfo["pay_type"]);
            }

            //回归任务充值活动任务
            $this->comBackService->comeBackeMissionStream($user_id, 1);
            //埋点
            $this->tdService->handleTrack('order_payment_finish', ['user_id'=>$user_id, 'order_id'=>$orderInfo['order_id']]);
            //充值成功则删除用户未支付订单缓存
            Redis::DECRBY($this->payOrderCountRedisKey.$user_id.':PAYTYPE:'.$orderInfo['pay_type'],1);
            //充值成功后改渠道1分钟充值缓存时间间隔
            Redis::SET($this->payOrderLimitReidsKey.$user_id.':PAYTYPE:'.$orderInfo['pay_type'],1);
            Redis::EXPIRE($this->payOrderLimitReidsKey.$user_id.':PAYTYPE:'.$orderInfo['pay_type'],60);
            return true;
        }
        write_log("app_pay", "notifyOp-03", $order_sn . ' - ' . $order_sn);
        redis_unlock('NOTIFYOP' . $order_sn);
        return true;
    }

    /**
     * 后台代充值
     * @param $user_id
     * @param $rule_id
     * @return bool
     */
    public function agent($user_id, $rule_id, &$order_sn,$rechargeType = 0)
    {
        $order_sn = create_recharge_order_sn();

        // 充值规格
        $ruleInfo = [];

        // TODO 判断充值类型获取规格数据
        switch ($rechargeType){
            case 0:// 钻石
                $ruleInfo = $this->diamond->getDiamondRuleAgent($rule_id);
                break;
            case 1:// 珍珠
                break;
            default:
                break;
        }

        if (empty($ruleInfo)){
            return false;
        }

        //充值黑名单
        $payBlack = $this->checkUserInRechargeBlack($user_id, 5);
        if($payBlack) {
            return Hint::FINANCE_RECHARGE_BLACK;
        }

        $this->rechargeOrder->create_order($order_sn, $user_id, $rule_id, $ruleInfo['diamond_amount'] ?? 0, $ruleInfo['price'], 5, 1000000,0,$rechargeType);
        $orderInfo = $this->rechargeOrder->getOrderBySn($order_sn);
        if($orderInfo['status'] == 0){
//            $desc = $this->config['wallet_change_desc']['recharge_diamond'];
            $desc = '充值-系统代充';
            $user_id = $orderInfo['user_id'];
            DB::beginTransaction();
            $this->rechargeOrder->changeOrderStatus($order_sn, $order_sn);

            // TODO 判断充值类型更新流水
            switch ($orderInfo['recharge_type'] ?? 0){
                case 0:// 钻石
                    $this->diamond->inc($user_id, 0, 0,3,$orderInfo['diamond_amount'] ?? 0,$desc);
                    $needSendMq = 1;
                    break;
                case 1:// 珍珠
                    break;
                default:
                    break;
            }

            DB::commit();

            if(!empty($needSendMq) && $needSendMq==1) {
                $this->rechargeOrder->orderPaySuccessToMQ($order_sn, $orderInfo['user_id']);
            }

            return true;
        }
        return true;
    }


    /**
     * 苹果充值
     * @param $user_id
     * @param $rule_id
     * @return bool
     */
    public function apple($user_id, $rule_id, $out_order_sn, $channel_id, &$order_sn,$rechargeType = 0)
    {
        if (!redis_lock('NOTIFYOP' . $out_order_sn, 5)){
            return false;
        }
        $order_sn = create_recharge_order_sn();

        // 充值规格
        $ruleInfo = [];

        // TODO 判断充值类型获取规格数据
        switch ($rechargeType){
            case 0:// 钻石
                $ruleInfo = $this->diamond->getDiamondRule($rule_id);
                break;
            case 1:// 珍珠

                break;
            default:
                break;
        }

        if (empty($ruleInfo)){
            redis_unlock('NOTIFYOP' . $out_order_sn);
            return false;
        }

        //充值黑名单
        $payBlack = $this->checkUserInRechargeBlack($user_id, 3);
        if($payBlack) {
            return Hint::FINANCE_RECHARGE_BLACK;
        }

        $old_order = $this->rechargeOrder->getOrderByOutsn($out_order_sn);
        if (!empty($old_order)){
            redis_unlock('NOTIFYOP' . $out_order_sn);
            return false;
        }
        $this->rechargeOrder->create_order($order_sn, $user_id, $rule_id, $ruleInfo['diamond_amount'] ?? 0, $ruleInfo['price'], 3, $channel_id, 0,$rechargeType);
        $orderInfo = $this->rechargeOrder->getOrderBySn($order_sn);
        $report_price = !empty($orderInfo['price']) ? $orderInfo['price']/100 : 0;
        if($orderInfo['status'] == 0){

            //埋点
            $this->tdService->handleTrack('order_payment_start', ['user_id'=>$user_id, 'order_id'=>$orderInfo['order_id']]);

            $desc = $this->config['wallet_change_desc']['recharge_diamond'];
            $user_id = $orderInfo['user_id'];
            DB::beginTransaction();
            $this->rechargeOrder->changeOrderStatus($order_sn, $out_order_sn);

            // TODO 判断充值类型更新流水
            switch ($orderInfo['recharge_type'] ?? 0){
                case 0:// 钻石
                    $this->diamond->inc($user_id, 0, 0,3,$orderInfo['diamond_amount'] ?? 0,$desc);
                    $needSendMq = 1;
                    break;
                case 1:// 珍珠

                    break;
                default:
                    break;
            }

            DB::commit();

            if(!empty($needSendMq) && $needSendMq==1) {
                $this->rechargeOrder->orderPaySuccessToMQ($order_sn, $orderInfo['user_id']);
            }

            redis_unlock('NOTIFYOP' . $out_order_sn);

            //埋点
            $this->tdService->handleTrack('order_payment_finish', ['user_id'=>$user_id, 'order_id'=>$orderInfo['order_id']]);

            //苹果充值上报推广
            // $this->report($user_id ,2 ,$report_price);
            return true;
        }
        redis_unlock('NOTIFYOP' . $out_order_sn);
        //苹果充值上报推广
        // $this->report($user_id ,2 ,$report_price);
        return true;
    }


    /**
     * 支付宝H5白名单获取所有用户数组
     * @return mixed
     */
    public function getAliPayH5WhiteArr(){
        return $this->rechargeOrder->getAliPayH5WhiteArr();

    }

    /**
     * 支付宝H5白名单删除用户
     * @param $userId
     * @return mixed
     */
    public function delAliPayH5White($userId){
        return $this->rechargeOrder->delAliPayH5White($userId);
    }


    /**
     * 支付宝H5白名单添加用户
     * @param $userId
     * @return mixed
     */
    public function addAliPayH5White($userId){
        return $this->rechargeOrder->addAliPayH5White($userId);
    }


    /**
     * 支付宝H5白名单获取用户
     * @param $userId
     * @return mixed
     */
    public function findAliPayH5White($userId){
        $data = [];
        if ($this->rechargeOrder->aliPayH5White($userId)){
            $data[] = $userId;
        }
        return $data;
    }

    /**归因上报
     * @param $user_id
     * @param int $type
     * @param int $price
     * @return bool
     */
    public function report($user_id, $type = 2 ,$price = 0)
    {
        if (empty($user_id) || !in_array($type, [0, 1, 2])) {
            return false;
        }
        //广告归因，上报付费
        $this->platformReportServices->reportPay($user_id, $price);

        return true;
    }

    /**设置充值历史记录
     * @param $params
     */
    public function setRechargeUser($params){
        return $this->rechargeOrder->setRechargeUser($params);
    }

    /**获取充值历史记录
     * @param $user_id
     * @return array
     */
    public function getRechargeUsers($user_id){
        $data = [];
        $user_ids = $this->rechargeOrder->getRechargeUser($user_id);
        if(!empty($user_ids)){
            $users = $this->user->get_users_by_ids($user_ids);
            foreach ($users as $user){
                $temp['user_uid'] = $user['user_uid'];
                $temp['nickname'] = mb_substr($user['nickname'] ,0,5) ;
                $temp['img'] = $user['images'][0] ?? '';
                $data[] = $temp;
            }
        }
        return $data;
    }

    //判断是否达到限额
    public function reachRechargeToplimit($userId) : bool{
        $toplimit = (new SystemConfig())->getRechargeTopLimit();
        if ($toplimit == null) {
            return false;
        }
        $rechargeTotal24 = $this->rechargeOrder->getRechargeTotal24($userId);
        if ($rechargeTotal24 >= $toplimit) {
            return true;
        }
        return false;
    }

    //判断用户是否在充值黑名单
    public function checkUserInRechargeBlack($userId, $pay_type){
        $info = $this->rechargeBlackModel->getRechargeBlack($userId, $pay_type);
        if(!empty($info)) {
            return 1;
        }
        return 0;
    }

    //获取用户实名状态
    public function checkUserConfirmStatus($userId, $rule_id)
    {
        $status = (new UserVerify())->isAdult($userId);
        $diamond = $this->rechargeOrder->getDiamondRule($rule_id);

        $minPrice = (new SystemConfig)->getPayMinpriceRealnamet();
        if ($minPrice !== '') {
            if ($diamond['diamond_amount'] >= $minPrice) {
                $user_verify = $this->userVerifyModel->getInfoByUser(['user_id' => $userId, 'result_code' => 1000]);
                if (empty($user_verify)) {
                    return false;
                }
            }
        } else if ($diamond['diamond_amount'] >= 1000) {
            $user_verify = $this->userVerifyModel->getInfoByUser(['user_id' => $userId, 'result_code' => 1000]);
            if (empty($user_verify)) {
                return false;
            }
        }
        if ($status == -1) {
            //查询未实名用户历史充总钻石数
            $allDiamondNum = $this->rechargeOrder->getRechargeDiamondTotal2($userId);
            if ($minPrice !== '') {
                if ($allDiamondNum >= $minPrice) {
                    return false;
                }
            } else if ($allDiamondNum >= 1000) {
                return false;
            }
        }
        return true;
    }

    public function checkUserConfirmStatusByMoney($userId, $money)
    {
        $status = (new UserVerify())->isAdult($userId);
        $minPrice = (new SystemConfig)->getPayMinpriceRealnamet();
        if ($minPrice !== '') {
            if ($money >= $minPrice) {
                $user_verify = $this->userVerifyModel->getInfoByUser(['user_id' => $userId, 'result_code' => 1000]);
                if (empty($user_verify)) {
                    return false;
                }
            }
        } else if ($money >= 1000) {
            $user_verify = $this->userVerifyModel->getInfoByUser(['user_id' => $userId, 'result_code' => 1000]);
            if (empty($user_verify)) {
                return false;
            }
        }
        if ($status == -1) {
            //查询未实名用户历史充总钻石数
            $allDiamondNum = $this->rechargeOrder->getRechargeDiamondTotal2($userId);
            if ($minPrice !== '') {
                if ($allDiamondNum >= $minPrice) {
                    return false;
                }
            } else if ($allDiamondNum >= 1000) {
                return false;
            }
        }
        return true;
    }


    //获取用户充值金额
    public function getRechargeTotal($userId){
        if(!empty($userId)) {
        $userRecharge = $this->rechargeOrder->getRechargeTotal($userId); //充值金额
        return empty($userRecharge)?0:$userRecharge/100;
        }

    }
}